#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>

void Task(){
    std::vector<int> data;
    int count = 1;
    while(count < 5){
	data.push_back(count++);
    }
    for(auto e : data){
	std::cout << e << " ";
    }
    std::cout << std::endl;
}


int main(){
    pid_t id = fork();
    if(id == 0){
        //child process
	while(1){
	    printf("i am subprocess, my pid:%d\n", getpid());
            sleep(1);
	}
    }
    else{
	//father process
	sleep(1);
	pid_t rid = waitpid(id, nullptr, WNOHANG);
	while(true){
	    sleep(1);
	    if(rid > 0){
	        //wait subprocess successfully and subprocess exit successfully
	        printf("成功等待子进程%d，且子进程已退出\n", rid);
	        break;
	    }
	    else if(rid == 0){
		//wait subprocess successfully but something wrong in subprocess exit
		printf("等待子进程成功%d，但子进程还没退出\n", rid); 
		//父进程干自己的事情
		Task();
	    }
	    else{
	    	//something wrong in waiting subprocess
		printf("等待子进程失败\n");
		break;
	    }
	}
    }
    return 0;
}
